package boun.swe.bob.dao;

import boun.swe.bob.entities.Friend;
import boun.swe.bob.entities.FriendsPK;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Component;

import java.sql.SQLException;
import java.util.List;

/**
 * This DAO corresponds to user_feeds table in database
 */
@Component
public class FriendDao extends GenericDaoImpl<Friend, FriendsPK> {
    
    private static final Logger LOG = Logger.getLogger(FriendDao.class);

    public void deleteFriend(final int userId1, final int userId2) {
        hibernateTemplate.execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Query query = session.createSQLQuery("delete from friends where (user1_id = ? and user2_id = ?) or (user1_id = ? and user2_id = ?)");
                query.setInteger(0, userId1);
                query.setInteger(1, userId2);
                query.setInteger(2, userId2);
                query.setInteger(3, userId1);

                query.executeUpdate();

                Query deleteFriendRequestQuery = session.createSQLQuery("delete from friend_requests where (requested_user_id = ? and requesting_user_id= ?) or (requesting_user_id = ? and requested_user_id= ?)");
                deleteFriendRequestQuery.setInteger(0, userId1);
                deleteFriendRequestQuery.setInteger(1, userId2);
                deleteFriendRequestQuery.setInteger(2, userId2);
                deleteFriendRequestQuery.setInteger(3, userId1);

                deleteFriendRequestQuery.executeUpdate();

                return null;
            }
        });
    }

    public List<Friend> getFriendsByUserId(final int UserId){
        return (List<Friend>) hibernateTemplate.execute(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Query query = session.createSQLQuery("select * from friends f where (f.user1_id = ? or f.user2_id = ?) and f.approved = 1").addEntity("f", Friend.class);
                query.setInteger(0, UserId);
                query.setInteger(1, UserId);
                return query.list();
            }
        });
    }

}
